import cgi
import os
import wsgiref.handlers
import postmarkup

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

# remove domain annotation from links
#postmarkup.LinkTag.annotate_link = lambda self, domain: u""

class Page(db.Model):
  user = db.UserProperty()
  title = db.StringProperty()
  content = db.TextProperty()
  public = db.BooleanProperty(default=False)
  public_id = db.StringProperty()
  views = db.IntegerProperty(default=0)
  created = db.DateTimeProperty(auto_now_add=True)
  updated = db.DateTimeProperty(auto_now=True)

class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()

    if user:
      pages = db.GqlQuery("SELECT * FROM Page WHERE user = :user ORDER BY created DESC", user = user)

      url = users.create_logout_url(self.request.uri)
      template_values = {
        'user': user,
        'pages': pages,
        'url': url,
        }

      path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
      self.response.out.write(template.render(path, template_values))
    else:
      self.redirect(users.create_login_url(self.request.uri))

class HelpPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    url = users.create_logout_url(self.request. uri)
    template_values= {
      'user': user,
      'url': url,
      }
    path = os.path.join(os.path.dirname(__file__), 'templates/help.html')
    self.response.out.write(template.render(path, template_values))

class ViewPage(webapp.RequestHandler):
  def get(self, page_key):
    user = users.get_current_user()
    if user:
      if page_key:
        page = db.get(page_key)
        if page.user == user:
          page.content = postmarkup.render_bbcode(page.content)
          
          user = users.get_current_user()
          url = users.create_logout_url(self.request.uri)
          
          template_values = {
            'user': user,
            'url': url,
            'page': page,
            }
          
          path = os.path.join(os.path.dirname(__file__), 'templates/view.html')
          self.response.out.write(template.render(path, template_values))
        else:
          self.redirect('/')
      else:
        self.redirect('/')
    else:
      self.redirect(users.create_login_url(self.request.uri))

class PublicPage(webapp.RequestHandler):
  def get(self, public_id):
    if public_id:
      query = Page.all()
      query.filter('public_id =', public_id)
      page = query.fetch(1)
      page = page[0]
      
      if page.public:
        page.views += 1
        page.put()
        page.content = postmarkup.render_bbcode(page.content)
        
        template_values = {
          'page': page,
          }
        
        path = os.path.join(os.path.dirname(__file__), 'templates/public.html')
        self.response.out.write(template.render(path, template_values))
      else:
        self.redirect('/')
    else:
      self.redirect('/')

class EditPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    
    if user:
      url = users.create_logout_url(self.request.uri)
      if self.request.get('key'):
        page = db.get(self.request.get('key'))
        if page.user != user:
          self.redirect('/')
        else:
          if self.request.get('public_id_alert'):
            template_values = {
              'page': page,
              'public_id_bad': self.request.get('public_id_alert'),
              'user': user,
              'url': url,
              }
          else:
            template_values = {
              'page': page,
              'user': user,
              'url': url,
            }
          
          path = os.path.join(os.path.dirname(__file__), 'templates/edit.html')
          self.response.out.write(template.render(path, template_values))
      else:
        template_values = {
          'user': user,
          'url': url,
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/edit.html')
        self.response.out.write(template.render(path, template_values))
    else:
      self.redirect(users.create_login_url(self.request.uri))

class SavePage(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    if user:
      public_id_alert = False
      if self.request.get('key'):
        page = db.get(self.request.get('key'))
      else:
        page = Page()

      if self.request.get('public'):
        page.public = True
        if self.request.get('public_id') != page.public_id:
          query = Page.all()
          query.filter('public_id =', self.request.get('public_id'))
          public = query.fetch(1)
          
          if public:
            public_id_alert = True
          else:
            page.public_id = self.request.get('public_id')
      else:
        page.public = False
      
      page.content = cgi.escape(self.request.get('content'))
      page.title = self.request.get('title')
      page.user = users.get_current_user()
      page.put()
      if public_id_alert:
        self.redirect('/edit?key=' + self.request.get('key') + '&public_id_alert=' + self.request.get('public_id'))
      else:
        self.redirect('/view/' + self.request.get('key'))
    else:
      self.redirect(users.create_login_url(self.request.uri))
    
class DeletePage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      page = db.get(self.request.get('key'))
      if page.user == user:
        if self.request.get('confirmed') == "yes":
          db.delete(page)
          self.redirect('/')
        else:
          template_values = {
            'page': page,
            }
          path = os.path.join(os.path.dirname(__file__), 'templates/delete.html')
          self.response.out.write(template.render(path, template_values))
      else:
        self.redirect('/')
    else:
      self.redirect(users.create_login_url(self.request.uri))

def main():
  application = webapp.WSGIApplication(
    [('/', MainPage),
     ('/create', EditPage),
     ('/delete', DeletePage),
     ('/edit', EditPage),
     ('/help', HelpPage),
     ('/p/(.*)', PublicPage),
     ('/save_page', SavePage),
     ('/view/(.*)', ViewPage)],
    debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
